package org.vaadin.example.security;

import com.mybatisflex.core.query.QueryWrapper;
import com.vaadin.flow.component.UI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.vaadin.example.biz.impl.UserQueryService;
import org.vaadin.example.orm.entity.SysAccount;
//import org.vaadin.example.orm.entity.table.AccountTableDef;
import org.vaadin.example.orm.entity.table.SysAccountTableDef;
import org.vaadin.example.orm.mapper.AccountMapper;
import org.vaadin.example.orm.entity.SRole;
//import org.vaadin.example.model.entity.table.AccountTableDef;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserDetailsService implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);


    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private UserQueryService userQueryService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysAccount sysAccount = accountMapper.selectOneByQuery(
                QueryWrapper.create().select().where(SysAccountTableDef.SYS_ACCOUNT.USER_NAME.eq(username))
        );
        if (sysAccount == null) {
            throw new UsernameNotFoundException(username);
        }
        List<SRole> userRoles = userQueryService.getUserRoles(username);

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (SRole role : userRoles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return new org.springframework.security.core.userdetails.User(sysAccount.getUserName(), sysAccount.getPassword(), authorities);
    }




}
